package com.mianshi;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
public class _Test {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void mockMvc() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }


    @org.junit.Test
    public void testHello() throws Exception {
        /*
         * 1、mockMvc.perform 执行一个请求。
         * 2、MockMvcRequestBuilders.get("XXX") 构造一个请求。
         * 3、ResultActions.param 添加请求传值
         * 4、ResultActions.accept(MediaType.TEXT_HTML_VALUE)) 设置返回类型
         * 5、ResultActions.andExpect 添加执行完成后的断言。
         * 6、ResultActions.andDo 添加一个结果处理器，表示要对结果做点什么事情
         *   比如此处使用MockMvcResultHandlers.print() 输出整个响应结果信息。
         * 7、ResultActions.andReturn 表示执行完成后返回相应的结果。
         */

        ResultActions action = mockMvc.perform(
                get("/order")
//                get("/hello")
                        .param("name", "Tom")
                        .param("password", "123456")
                        .contentType(MediaType.APPLICATION_JSON)

        );

        String result = action
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();

        System.out.println("返回结果==" + result);

    }

    @org.junit.Test
    public void uploadFile() throws Exception {
        String result = mockMvc.perform(fileUpload("/file")
                .file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello upload".getBytes("UTF-8"))))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);

    }


}
